package com.chat.websocket.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.chat.constant.tab.MessageConstant;
import com.chat.dao.ChatPeopleRelationDao;
import com.chat.dao.LeaveMsgDao;
import com.chat.entity.TdChatLeaveMsg;
import com.chat.entity.TdChatPeopleRelationWithBLOBs;
import com.chat.vo.back.OneChatBodyVo;
import com.chat.vo.back.OneChatJsonVo;
import com.chat.vo.back.ReqFriendShipBodyVo;
import com.chat.vo.back.ReqFriendShipJsonVo;
import com.chat.vo.back.ResFriendShipBodyVo;
import com.chat.vo.back.ResFriendShipJsonVo;
import com.chat.vo.params.OnlinePeopleVo;
import com.chat.websocket.online.OnlineManage;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 一对一聊天业务
 *@author zh_zhong
 */
@Service
@Transactional
public  class OneToOneChatService {
	
	@Autowired
	private LeaveMsgDao leaveMsgDao;
	
	@Autowired
	private ChatPeopleRelationDao peopleRelationDao;
	
	
	/**
	 * 发送添加好友请求
	 * 
	 */
	public void sendRequestFriendShipMsg(String fromUserName, 
			String toUserName)throws IOException{
		
		ReqFriendShipJsonVo msg = new ReqFriendShipJsonVo();
		msg.setType(MessageConstant.RequestFriendShip);
		msg.setStatus("success");
		ReqFriendShipBodyVo body = new ReqFriendShipBodyVo();
		body.setDate(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
		body.setFromUser(fromUserName);
		body.setMessage("用户" +fromUserName+ "请求添加你为好友");
		msg.setBody(body);
		String jsonMsg = new ObjectMapper().writeValueAsString(msg);
		
		OnlinePeopleVo toUser = OnlineManage.getOnlineUser(toUserName);
		WebSocketSession webSocketSession = toUser.getSession();
		webSocketSession.sendMessage(new TextMessage(jsonMsg));
	
	}
	
	
	/**
	 * 保存添加好友请求的离线信息
	 * @param fromUserName
	 * @param toUserName
	 */
	public void saveRequestFriendShipMsg(String fromUserName, String toUserName){
		
		TdChatLeaveMsg msg = new TdChatLeaveMsg();
		msg.setBody("用户" +fromUserName+ "请求添加你为好友");
		msg.setBodytype(1);
		msg.setCreatetime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
		msg.setFromuser(fromUserName);
		msg.setIspushed(0);
		msg.setLeavetype(MessageConstant.RequestFriendShip);
		msg.setTousers(toUserName);
		
		leaveMsgDao.insertOneLeaveMsg(msg);	
	}
	
	/**
	 * 双向建立好友关系
	 * @param fromUserName
	 * @param toUserName
	 */
	public void buildFriendShip(String toUserName, String fromUserName){
		
		TdChatPeopleRelationWithBLOBs fromUser = peopleRelationDao.selectByUserName(fromUserName);
		TdChatPeopleRelationWithBLOBs toUser = peopleRelationDao.selectByUserName(toUserName);
		
		//为fromUser添加toUser为好友
		if (fromUser != null){
			
			String friends = fromUser.getFriendsid();
			if (friends != null){
				fromUser.setFriendsid(friends + "," +toUserName);
			}else{
				fromUser.setFriendsid(toUserName);
			}
			fromUser.setFriendnum(fromUser.getFriendnum()+1);
			
			peopleRelationDao.updateByPrimaryKeyWithBLOBs(fromUser);
			
		}else{
			fromUser = new TdChatPeopleRelationWithBLOBs();
			fromUser.setCreated(new Date());
			fromUser.setFriendnum(1);
			fromUser.setFriendsid(toUserName);
			fromUser.setUsername(fromUserName);
			
			peopleRelationDao.insertSelective(fromUser);
		}
		
		//为toUser添加fromUser为好友
		if (toUser != null){
					
			String friends = toUser.getFriendsid();
			if (friends != null){
				toUser.setFriendsid(friends + "," +fromUserName);
			}else{
				toUser.setFriendsid(fromUserName);
			}
			toUser.setFriendnum(toUser.getFriendnum()+1);
			
			peopleRelationDao.updateByPrimaryKeyWithBLOBs(toUser);
					
		}else{
			toUser = new TdChatPeopleRelationWithBLOBs();
			toUser.setCreated(new Date());
			toUser.setFriendnum(1);
			toUser.setFriendsid(fromUserName);
			toUser.setUsername(toUserName);
			
			peopleRelationDao.insertSelective(toUser);
		}
		
		
	}
	
	/**
	 * 好友请求结果通知
	 * @param fromUserName
	 * @param userName
	 * @param isAgree 是否同意
	 */
	public void sendRequestFriendShipResult(String fromUserName, String userName,
			boolean isAgree)throws IOException{
		String msg = null;
		if (isAgree){
			msg = "用户" +userName+ "同意添加你为好友";
		}else{
			msg = "用户" +userName+ "不同意添加你为好友";
		}
		
		ResFriendShipJsonVo res = new ResFriendShipJsonVo();
		res.setStatus("success");
		res.setType(MessageConstant.ReponseFriendShip);
		ResFriendShipBodyVo body = new ResFriendShipBodyVo();
		body.setDate(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
		body.setFromUserName(userName);
		body.setMessage(msg);
		res.setBody(body);
		
		String jsonMsg = new ObjectMapper().writeValueAsString(res);
		
		OnlinePeopleVo fromUser = OnlineManage.getOnlineUser(fromUserName);
		WebSocketSession webSocketSession = fromUser.getSession();
		webSocketSession.sendMessage(new TextMessage(jsonMsg));
		
	}
	
	/**
	 * 在线单聊;
	 * @param userName
	 * @param toUserName
	 * @param message
	 */
	public void sendMsg(String userName, String toUserName,
			String message, Integer msgType)throws IOException{
		
		OneChatJsonVo msg = new OneChatJsonVo();
		msg.setStatus("success");
		msg.setType(MessageConstant.OneToOne);
		OneChatBodyVo body = new OneChatBodyVo();
		body.setData(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
		body.setFromUser(userName);
		body.setMessage(message);
		body.setMsgType(msgType);
		msg.setBody(body);
		
		String jsonMsg = new ObjectMapper().writeValueAsString(msg);
		OnlinePeopleVo toUser = OnlineManage.getOnlineUser(toUserName);
		WebSocketSession webSocketSession = toUser.getSession();
		webSocketSession.sendMessage(new TextMessage(jsonMsg));
		
		
	}
	
	/**
	 * 保存一对一聊天的离线信息
	 * @param userName
	 * @param toUserName
	 * @param message
	 */
	public void saveUnsendMsg(String userName, String toUserName,
			String message, Integer msgType){
		TdChatLeaveMsg model = new TdChatLeaveMsg();
		model.setBody(message);
		model.setBodytype(msgType);
		model.setCreatetime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
		model.setFromuser(userName);
		model.setIspushed(0);
		model.setLeavetype(MessageConstant.OneToOne);
		model.setTousers(toUserName);
		
		leaveMsgDao.insertOneLeaveMsg(model);
		
	}
	
	/**
	 * 解除好友关系
	 * @param userName
	 * @param toUserName
	 */
	public void removeFriendShip(String userName, String toUserName){
		TdChatPeopleRelationWithBLOBs fromUser = peopleRelationDao.selectByUserName(userName);
		TdChatPeopleRelationWithBLOBs toUser = peopleRelationDao.selectByUserName(toUserName);
	
		Pattern pattern = null;
		Matcher matcher = null;
		
		if (fromUser != null){
			String friends = fromUser.getFriendsid();
			if (friends != null){
				pattern = Pattern.compile(toUserName+",|," +toUserName);
				matcher = pattern.matcher(friends);
				friends = matcher.replaceAll("");
				
				fromUser.setFriendsid(friends);
				peopleRelationDao.updateByPrimaryKeyWithBLOBs(fromUser);
				
			}
		}
		
		if (toUser != null){
			String friends = toUser.getFriendsid();
			if (friends != null){
				pattern = Pattern.compile(userName+",|," +userName);
				matcher = pattern.matcher(friends);
				friends = matcher.replaceAll("");
				
				toUser.setFriendsid(friends);
				peopleRelationDao.updateByPrimaryKeyWithBLOBs(toUser);
				
			}
		}
	}


}
